﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Jungle.Code.DAL;
using Jungle.Code.Utils;
using System.Data.SqlClient;
using System.Data;

using Jungle.Code.CategoryManager;


namespace Jungle.Code.ProductManager
{
    public class Product
    {
        public string err = ""; //основной поток ошибок
        private string ConnectionString = DBHelper.ConnectionString;

        public List<Product> ProductsList;

        #region Fields

        private int productId; //идентификатор продукта
        private string title; //название
        private string description; //описание
        private string catalogNumber; //каталожный номер
        private double marketPrice; //рыночная цена
        private double price; //цена сайта
        private int minimalOrder; //минимальный заказ (штук)
        private double weight; //вес товара
        private int typeId; //тип товара
        private string imagePath; //путь к изображению товара
        private int categoryId; //категория каталога в которой расположен товар
        private bool visible; //видно ли в основном каталоге
        private DateTime addDate; //дата добавления продукта

        #endregion

        #region Properties
        /// <summary>
        /// индивидуальный идентификатор продукта в базе данных
        /// </summary>
        public int ProductId { get { return productId; } set { productId = value; } }
        /// <summary>
        /// название продукта в базе данных
        /// </summary>
        public string Title { get { return title; } set { title = value; } }
        /// <summary>
        /// описание продукта
        /// </summary>
        public string Description { get { return description; } set { description = value; } }
        /// <summary>
        /// каталожный номер
        /// </summary>
        public string CatalogNumber { get { return catalogNumber; } set { catalogNumber = value; } }
        /// <summary>
        /// рыночная цена
        /// </summary>
        public double MarketPrice { get { return marketPrice; } set { marketPrice = value; } }
        /// <summary>
        /// цена на сайте
        /// </summary>
        public double Price { get { return price; } set { price = value; } }
        /// <summary>
        /// минимальный заказ (штук)
        /// </summary>
        public int MinimalOrder { get { return minimalOrder; } set { minimalOrder = value; } }
        /// <summary>
        /// вес продукта
        /// </summary>
        public double Weight { get { return weight; } set { weight = value; } }
        /// <summary>
        /// тип продукта (книга, одежда, икона, благовония и т.д.)
        /// </summary>
        public int TypeId { get { return typeId; } set { typeId = value; } }
        /// <summary>
        /// путь к изображению продукта
        /// </summary>
        public string ImagePath { get { return imagePath; } set { imagePath = value; } }
        /// <summary>
        /// указывает на расположение в определенной категории каталога
        /// </summary>
        public int CategoryId { get { return categoryId; } set { categoryId = value; } }
        /// <summary>
        /// видимость товара в каталоге
        /// </summary>
        public bool Visible { get { return visible; } set { visible = value; } }
        /// <summary>
        /// дата добавления продукта в базу
        /// </summary>
        public DateTime AddDate { get { return addDate; } set { addDate = value; } }


        #endregion

        //---------------------------------------------------------------------
        public void Add()
        {
            SqlConnection connect = new SqlConnection(ConnectionString);
            SqlCommand command = new SqlCommand("catalog.Product_Add", connect);
            command.CommandType = CommandType.StoredProcedure;
            try
            {
                command.Parameters.Add("@Title", SqlDbType.VarChar).Value = Title;
                command.Parameters.Add("@Description", SqlDbType.VarChar).Value = Description;
                command.Parameters.Add("@CatalogNumber", SqlDbType.VarChar).Value = CatalogNumber;
                command.Parameters.Add("@MarketPrice", SqlDbType.Float).Value = MarketPrice;
                command.Parameters.Add("@Price", SqlDbType.Float).Value = Price;
                command.Parameters.Add("@MinimalOrder", SqlDbType.Int).Value = MinimalOrder;
                command.Parameters.Add("@Weight", SqlDbType.Float).Value = Weight;
                command.Parameters.Add("@TypeId", SqlDbType.Int).Value = TypeId;
                command.Parameters.Add("@ImagePath", SqlDbType.VarChar).Value = ImagePath;
                command.Parameters.Add("@CategoryId", SqlDbType.Int).Value = CategoryId;
                command.Parameters.Add("@Visible", SqlDbType.Bit).Value = Visible;
                command.Parameters.Add("@AddDate", SqlDbType.DateTime).Value = DateTime.Now;

                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                err = ex.ToString();

            }
            finally
            {
                command.Connection.Close();
            }
        }
        //---------------------------------------------------------------------
        public void Update()
        {
            SqlConnection connect = new SqlConnection(ConnectionString);
            SqlCommand command = new SqlCommand("catalog.Product_Update", connect);
            command.CommandType = CommandType.StoredProcedure;
            try
            {
                command.Parameters.Add("@ProductId", SqlDbType.Int).Value = ProductId;
                command.Parameters.Add("@Title", SqlDbType.VarChar).Value = Title;
                command.Parameters.Add("@Description", SqlDbType.VarChar).Value = Description;
                command.Parameters.Add("@CatalogNumber", SqlDbType.VarChar).Value = CatalogNumber;
                command.Parameters.Add("@MarketPrice", SqlDbType.Float).Value = MarketPrice;
                command.Parameters.Add("@Price", SqlDbType.Float).Value = Price;
                command.Parameters.Add("@MinimalOrder", SqlDbType.Int).Value = MinimalOrder;
                command.Parameters.Add("@Weight", SqlDbType.Float).Value = Weight;
                command.Parameters.Add("@TypeId", SqlDbType.Int).Value = TypeId;
                command.Parameters.Add("@ImagePath", SqlDbType.VarChar).Value = ImagePath;
                command.Parameters.Add("@CategoryId", SqlDbType.Int).Value = CategoryId;
                command.Parameters.Add("@Visible", SqlDbType.Bit).Value = Visible;
                                

                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                err = ex.ToString();

            }
            finally
            {
                command.Connection.Close();
            }
        }
        //---------------------------------------------------------------------
        public int GetByType(int tId)
        {
            int count = 0;
            using (SqlConnection connect = new SqlConnection(ConnectionString))
            {
                ProductsList = new List<Product>();
                SqlCommand command = new SqlCommand("catalog.Product_GetByType", connect);
                SqlDataReader reader = null;

                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@TypeId", SqlDbType.Int).Value = tId;

                command.Connection.Open();
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    Product p = new Product();
                    p.ProductId = (int)reader["ProductId"];
                    p.Title = reader["Title"].ToString().Trim();
                    p.Description = reader["Description"].ToString().Trim();
                    p.CatalogNumber = reader["CatalogNumber"].ToString().Trim();
                    p.MarketPrice = (double)reader["MarketPrice"];
                    p.Price = (double)reader["Price"];
                    p.MinimalOrder = (int)reader["MinimalOrder"];
                    p.Weight = (double)reader["Weight"];
                    p.TypeId = (int)reader["TypeId"];
                    p.ImagePath = reader["ImagePath"].ToString().Trim();
                    p.CategoryId = (int)reader["CategoryId"];
                    p.Visible = (bool)reader["Visible"];
                    p.addDate = (DateTime)reader["AddDate"];
                    

                    ProductsList.Add(p);
                    count++;
                }

                reader.Close();
                command.Connection.Close();

            }
            return count; 
        }
        //---------------------------------------------------------------------
        public void GetByProductId()
        {
            using (SqlConnection connect = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("catalog.Product_GetById", connect);
                SqlDataReader reader = null;

                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@ProductId", SqlDbType.Int).Value = ProductId;

                command.Connection.Open();
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    Title = reader["Title"].ToString().Trim();
                    Description = reader["Description"].ToString().Trim();
                    CatalogNumber = reader["CatalogNumber"].ToString().Trim();
                    MarketPrice = (double)reader["MarketPrice"];
                    Price = (double)reader["Price"];
                    MinimalOrder = (int)reader["MinimalOrder"];
                    Weight = (double)reader["Weight"];
                    TypeId = (int)reader["TypeId"];
                    ImagePath = reader["ImagePath"].ToString().Trim();
                    CategoryId = (int)reader["CategoryId"];
                    Visible = (bool)reader["Visible"];
                    AddDate = (DateTime)reader["AddDate"];
                }

                reader.Close();
                command.Connection.Close();

            }

        }
        //---------------------------------------------------------------------
        public int GetByCategoryId(int catId) //возвращает количество найденых в каталоге товаров
        {
            int count = 0;
            using (SqlConnection connect = new SqlConnection(ConnectionString))
            {
                ProductsList = new List<Product>();
                SqlCommand command = new SqlCommand("catalog.Product_GetByCategoryId", connect);
                SqlDataReader reader = null;

                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@CategoryId", SqlDbType.Int).Value = catId;

                command.Connection.Open();
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    Product p = new Product();
                    p.ProductId = (int)reader["ProductId"];
                    p.Title = reader["Title"].ToString().Trim();
                    p.Description = reader["Description"].ToString().Trim();
                    p.CatalogNumber = reader["CatalogNumber"].ToString().Trim();
                    p.MarketPrice = (double)reader["MarketPrice"];
                    p.Price = (double)reader["Price"];
                    p.MinimalOrder = (int)reader["MinimalOrder"];
                    p.Weight = (double)reader["Weight"];
                    p.TypeId = (int)reader["TypeId"];
                    p.ImagePath = reader["ImagePath"].ToString().Trim();
                    p.CategoryId = (int)reader["CategoryId"];
                    p.Visible = (bool)reader["Visible"];
                    p.AddDate = (DateTime)reader["AddDate"];

                    ProductsList.Add(p);
                    count++;
                }

                reader.Close();
                command.Connection.Close();

            }
            return count;
        }
        //---------------------------------------------------------------------
        public void Delete()
        {
            SqlConnection connect = new SqlConnection(ConnectionString);
            SqlCommand command = new SqlCommand("catalog.Product_Delete", connect);
            command.CommandType = CommandType.StoredProcedure;
            try
            {
                command.Parameters.Add("@ProductId", SqlDbType.Int).Value = ProductId;

                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                err = ex.ToString();

            }
            finally
            {
                command.Connection.Close();
            }
        }
        //---------------------------------------------------------------------
        public void Hide()
        {
            SqlConnection connect = new SqlConnection(ConnectionString);
            SqlCommand command = new SqlCommand("catalog.Product_Hide", connect);
            command.CommandType = CommandType.StoredProcedure;
            try
            {
                command.Parameters.Add("@ProductId", SqlDbType.Int).Value = ProductId;

                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                err = ex.ToString();

            }
            finally
            {
                command.Connection.Close();
            }
        }
        //---------------------------------------------------------------------
        public void UnHide()
        {
            SqlConnection connect = new SqlConnection(ConnectionString);
            SqlCommand command = new SqlCommand("catalog.Product_UnHide", connect);
            command.CommandType = CommandType.StoredProcedure;
            try
            {
                command.Parameters.Add("@ProductId", SqlDbType.Int).Value = ProductId;

                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                err = ex.ToString();

            }
            finally
            {
                command.Connection.Close();
            }
        }
        //---------------------------------------------------------------------
        public int GetHiddenProducts()
        {
            int count = 0;
            using (SqlConnection connect = new SqlConnection(DBHelper.ConnectionString))
            {
                ProductsList = new List<Product>();
                SqlCommand command = new SqlCommand("catalog.Product_GetHidden", connect);
                SqlDataReader reader = null;

                command.CommandType = CommandType.StoredProcedure;
                
                command.Connection.Open();
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    Product p = new Product();
                    p.ProductId = (int)reader["ProductId"];
                    p.Title = reader["Title"].ToString().Trim();
                    p.Description = reader["Description"].ToString().Trim();
                    p.CatalogNumber = reader["CatalogNumber"].ToString().Trim();
                    p.MarketPrice = (double)reader["MarketPrice"];
                    p.Price = (double)reader["Price"];
                    p.MinimalOrder = (int)reader["MinimalOrder"];
                    p.Weight = (double)reader["Weight"];
                    p.TypeId = (int)reader["TypeId"];
                    p.ImagePath = reader["ImagePath"].ToString().Trim();
                    p.CategoryId = (int)reader["CategoryId"];
                    p.Visible = (bool)reader["Visible"];
                    p.AddDate = (DateTime)reader["AddDate"];
                    
                    ProductsList.Add(p);
                    count++;
                }

                reader.Close();
                command.Connection.Close();

            }
            return count;
        }
        //---------------------------------------------------------------------
        public int GetAllProducts()
        {
            int count = 0;
            using (SqlConnection connect = new SqlConnection(DBHelper.ConnectionString))
            {
                ProductsList = new List<Product>();
                SqlCommand command = new SqlCommand("SELECT * FROM catalog.Products where [Visible] = 'True' order by AddDate", connect);
                SqlDataReader reader = null;

                command.CommandType = CommandType.Text;

                command.Connection.Open();
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    Product p = new Product();
                    p.ProductId = (int)reader["ProductId"];
                    p.Title = reader["Title"].ToString().Trim();
                    p.Description = reader["Description"].ToString().Trim();
                    p.CatalogNumber = reader["CatalogNumber"].ToString().Trim();
                    p.MarketPrice = (double)reader["MarketPrice"];
                    p.Price = (double)reader["Price"];
                    p.MinimalOrder = (int)reader["MinimalOrder"];
                    p.Weight = (double)reader["Weight"];
                    p.TypeId = (int)reader["TypeId"];
                    p.ImagePath = reader["ImagePath"].ToString().Trim();
                    p.CategoryId = (int)reader["CategoryId"];
                    p.Visible = (bool)reader["Visible"];
                    p.AddDate = (DateTime)reader["AddDate"];

                    ProductsList.Add(p);
                    count++;
                }

                reader.Close();
                command.Connection.Close();

            }
            return count;
        }
        //------------------------------------------------------------------------
        public int GetRSSByCategory(int CatId)
        {
            int count = 0;
            try
            {
                using (SqlConnection connect = new SqlConnection(ConnectionString))
                {
                    ProductsList = new List<Product>();
                    SqlCommand command = new SqlCommand("dbo.RSS_GetNewsByCategory", connect);
                    SqlDataReader reader = null;

                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add("@CategoryId", SqlDbType.Int).Value = CatId;

                    command.Connection.Open();
                    reader = command.ExecuteReader();

                    if (reader == null) { return 0; }

                    while (reader.Read())
                    {
                        Product pr = new Product();
                        pr.ProductId = (int)reader["ProductId"];
                        pr.Title = reader["Title"].ToString().Trim();
                        pr.Description = reader["Description"].ToString().Trim();
                        pr.Price = (double)reader["Price"];
                        pr.ImagePath = reader["ImagePath"].ToString().Trim();
                        ProductsList.Add(pr);
                        count++;
                    }

                    reader.Close();

                    command.Connection.Close();

                }
                return count;
            }
            catch
            {
                return 0;
            }
        }

    }
}
